package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.article.HotArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        //校验参数 文章id必须传
        //获取设备id
        Integer equipmentId = dto.getEquipmentId();
        //判断文章是否存在
        if (dto.getArticleId() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在，无法进行该操作");
        }
        //根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        //判断用户是否存在
        if (user == null) {
            //判断用户不存在的情况下，设备是否存在
            ApUser apUser = new ApUser();
            ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(apUser.getId(), dto.getEquipmentId());
            if (apBehaviorEntry == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "无法进行该操作");
            }
            //判断阅读行为是否存在
            ApReadBehavior apReadBehavior = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId())), ApReadBehavior.class);
            //存在  将阅读行为的count字段加1 并修改
            extracted(dto, apReadBehavior);
            //不存在  创建阅读行为 并初始化count字段值为 1
            estracted(dto);
        } else {
            //判断阅读行为是否存在
            ApReadBehavior apReadBehavior = mongoTemplate.findOne(Query.query(Criteria.where("articleId").is(dto.getArticleId())), ApReadBehavior.class);
            //存在  将阅读行为的count字段加1 并修改
            extracted(dto, apReadBehavior);
            //不存在  创建阅读行为 并初始化count字段值为 1
            estracted(dto);
        }
        NewBehaviorDTO mess = new NewBehaviorDTO();
        mess.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE,
                JSON.toJSONString(mess)  //如果是json序列化，直接发对象
                //如果没有设置序列化，发送json字符串消息
        );
        log.info("成功发送阅读行为消息 消息内容：{}",mess);

        return ResponseResult.okResult();
    }

    private void estracted(ReadBehaviorDTO dto) {
        ApReadBehavior apReadBehavior;
        apReadBehavior = new ApReadBehavior();
        apReadBehavior.setEntryId(apReadBehavior.getId());
        apReadBehavior.setArticleId(dto.getArticleId());
        apReadBehavior.setCount((short) 1);
        apReadBehavior.setCreatedTime(new Date());
        mongoTemplate.insert(apReadBehavior);
    }


    private void extracted(ReadBehaviorDTO dto, ApReadBehavior apReadBehavior) {
        if (apReadBehavior != null) {
            Short count = apReadBehavior.getCount();
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()));
            Update update = new Update();
            update.set("count",(short) (count + 1));
            mongoTemplate.updateFirst(query,update, ApReadBehavior.class);
        }
    }
}
